import React, {useEffect, useRef, forwardRef, useImperativeHandle, useState} from 'react';
import { Col,Select, Form, Button, message, Tooltip } from 'antd';
import PolicyCommonMent from './policyCommonMent';
import services from '../../../services/api';
import moment from 'moment';
import { cloneDeep } from 'lodash';
import '../index.less'
const { Option } = Select;
function teps2(props, forwardedRef) {
  const [stargyData, setStargyData] = useState({});
  const [ruleList, setRuleList] = useState([]);
  const [showLeftBtn, setLeftBtn] = useState(false);
  const [showRightBtn, setRightBtn] = useState(false);
  const [submitData, setSubmitData] = useState([]);
  const childNode = useRef(null);
  useEffect(()=>{
    getRuleList(props.requestParam.app_id, props.requestParam.event_id, props.requestParam.product_id);
  },[props.requestParam])
  useEffect(() => {
    if (props.tabsClick === '3' && Object.keys(props.requestParam).length && submitData.length) {
      stargyHit(); // 类型改了请求数据
    }
  },[props.stepType, props.grainType, props.requestParam, props.timeType, props.tabsClick]);
  useImperativeHandle(forwardedRef, () => ({
    downData
  }));
  // 规则
  function getRuleList(app_id, event_id, product_id) {
    const params = {};
    if (props.echoParams) {
      params.report_id = props.echoParams.report_id
      params.send_time = props.echoParams.send_time
      params.token = props.echoParams.token
    }
    services[props.actionType].ruleList({ app_id, event_id, product_id, type:1, ...params}).then((res) => {
      if (!res.code) {
        const lits = res.data.map(it => {
           if (it.name) {
             it.label = `${it.name}(${it.strategy_name})`
           } else {
            it.label = it.rule_id
           }
           return it
        })
        if (lits.length) {
          const rules = [lits[0].rule_id];
          setSubmitData(rules);
          stargyHit(rules);
          setRuleList(lits);
        }
      } else {
        message.error(res.msg);
      }
    });
  };
  function downData() {
    let params =  getParamsData(submitData);
    return params
  };
  function getParamsData(data) {
    let count = childNode.current.preveIndex;
    let isHideRight = false;
    let rule_ids = submitData;
    if (typeof data === 'number') {
      count = data;
      isHideRight = true;
    } else if (data && typeof data !== 'number') {
      rule_ids = data;
      count = 0;
      childNode.current.setPreveFn();
    } else {
      count = 0;
      childNode.current.setPreveFn();
    }
    const times = childNode.current.getCurrentTime(props.timeType, count);
    if (!isHideRight || !count) {
      setRightBtn(false);
    } else if (isHideRight) {
      if (count) {
        setRightBtn(true);
      }
    }
    if (moment(times.current_start) >= moment(times.current_end)) {
      setLeftBtn(true);
    } else {
      setLeftBtn(false);
    }
    if (moment(times.current_start) >= moment(props.requestParam.start)) {
      setLeftBtn(true);
    } else {
      times.current_start = props.requestParam.start;
    };
    const params = {
      ...props.requestParam,
      level: props.stepType,
      type: props.timeType,
      rule_ids: rule_ids,
      ...times
    }
    return params;
  };
  function nextFn(data) {
    stargyHit(data);
    if (!data) {
      setRightBtn(false);
    } else {
      setRightBtn(true);
    }
  };
  // 请求策略命中
  function stargyHit(data) {
    let params = getParamsData(data);
    services[props.actionType].ruleTrend(params).then(res => {
       if (!res.code) {
        const lits = reastData(cloneDeep(res.data));
        setStargyData(lits);
       } else {
         message.error(res.msg);
       }
    });
  };
  // 重置数据
  function reastData(data) {
    if (props.grainType === 'request' || !Object.keys(stargyData).length) return data;
    data.hit_ranking = data.hit_ranking.map(it => {
      it.value = (it.count && ((it.value / it.count) * 10000).toFixed() / 100) || 0;
      return it;
    });
    data.hit_trend = data.hit_trend.map(it => {
      it.value = it.value.map(item => {
          item.requests = (it.count && ((item.requests / it.count) * 10000).toFixed() / 100) || 0;
          return item;
       })
       return it;
    })
    return data;
  };
  function changeValues(rule ,value , callback) {
    if (!value.length) {
      callback('请选择规则');
    } else {
    　if (value.length > 5){
    　　 callback('最多选择五条规则');
    　} else {
    　　 callback();
    　}
    }
  };
  const components = (<Form
    name="customized_form_controls"
    layout="inline"
    className='select-max'
    onSubmit={() => false}
  >
    <Form.Item name="price" label="规则名称">
      {props.form.getFieldDecorator('rule_ids',{
        initialValue: submitData,
        rules:  [
          { required: true, validator : changeValues },
        ],
      })(<Select mode="multiple" style={{ width: '300px' }} placeholder="请选择规则" showArrow={true}>
        {ruleList.map(item => {
          return (<Option key={item.rule_id} value={item.rule_id}><Tooltip placement='topLeft' title={item.label}>{item.label}</Tooltip></Option>)
        })}
      </Select>)
     }
    </Form.Item>
    <Form.Item>
      <Button type="primary" onClick={handleSumit}>
        确定
      </Button>
    </Form.Item>
  </Form>)
  const renders = (record, index) => {
    return (
      <>
        <span style={{ marginRight: '10px' }}>{index + 1}</span>
        {record.id + (record.name && ("(" + record.name + ")")) || ''}
      </>
    );
  }
  function handleSumit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        setSubmitData(values.rule_ids);
        stargyHit(values.rule_ids);
      }
    })
  }
  return (
    <>
      <Col key={1} span={24}>
        <PolicyCommonMent
          {...props}
          lineTitle='规则命中趋势'
          progressTitle='规则命中排名'
          component={components}
          ref={childNode}
          showLeftBtn={showLeftBtn}
          showRightBtn={showRightBtn}
          nextFn={nextFn}
          trendList={stargyData.hit_trend || []}
          leftLabel='规则'
          rightLabel={props.grainType === 'request' ? '命中次数' : '命中比率'}
          keyValue={['id', 'value']}
          dataSource={stargyData.hit_ranking || []}
          total={props.grainType === 'request' ? ((stargyData.hit_ranking && stargyData.hit_ranking.length) ? stargyData.hit_ranking[0].count : 100) : 100}
          renderLabel={renders}
          renderValue= {(record, index) => {
            return props.grainType=== 'request' ? record.value : (record.value +'%')
            }
          }
        ></PolicyCommonMent>
      </Col>
    </>
  )
}
export default forwardRef(teps2)